package com.zkingsoft.zkingbase.manager;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;

import com.google.gson.Gson;
import com.google.gson.internal.$Gson$Types;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMVideo;
import com.umeng.socialize.media.UMusic;
import com.zkingsoft.zkingbase.bean.resp.UMQQResp;
import com.zkingsoft.zkingbase.bean.resp.UMSINAResp;
import com.zkingsoft.zkingbase.bean.resp.UMWXResp;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Created by ytf on 2016/11/9.
 */
public class UMManager
{
    private static UMManager mInstance;

    private UMManager()
    {
    }

    public static UMManager newInstance()
    {
        if (mInstance == null)
        {
            synchronized (UMManager.class)
            {
                if (mInstance == null)
                {
                    mInstance = new UMManager();
                }
            }
        }
        return mInstance;
    }

    /***
     * 分享文字
     * @param activity
     * @param   type    平台
     * @param shareContent 分享内容
     * @param title 标题
     * @param umShareListener  回调
     */
    public void shareText(Activity activity, SHARE_MEDIA type, String shareContent, String title, UMShareListener umShareListener)
    {
        new ShareAction(activity).setPlatform(type)
                .withText(shareContent)
                .setCallback(umShareListener)
                .share();
    }

    /***
     * 分享图片
     * @param   activity
     * @param type  平台
     * @param shareContent  分享内容可以是 String链接、File、Integer(资源引用)、Bitmap、byte[]字节数组
     * @param title 标题
     * @param umShareListener 回调
     */
    public void shareImage(Activity activity, SHARE_MEDIA type, Object shareContent, String title,UMShareListener umShareListener)
    {

        UMImage image = null;
        if (shareContent != null)
        {
            if (shareContent instanceof String)
            {
                String url = (String)shareContent;
                image = new UMImage(activity, url);//网络图片
            }
            if (shareContent instanceof File)
            {
                File file = (File)shareContent;
                image = new UMImage(activity, file);//本地图片
            }
            if (shareContent instanceof Integer)
            {
                Integer drawableId = (Integer)shareContent;
                image = new UMImage(activity, drawableId);//资源图片
            }
            if (shareContent instanceof Bitmap)
            {
                Bitmap bmp = (Bitmap)shareContent;
                image = new UMImage(activity, bmp);//位图
            }
            if (shareContent instanceof byte[])
            {
                byte[] buffer = (byte[])shareContent;
                image = new UMImage(activity, buffer);//网络图片
            }
            new ShareAction(activity)
                    .setPlatform(type)
                    .withMedia(image)
                    .setCallback(umShareListener)
                    .share();
        }
    }

    /***
     * 分享音乐，有问题，不能用，分享成功后打开是友盟官网。。。
     * @param activity
     * @param type  平台
     * @param musicurl 音乐链接
     * @param musicThumb 音乐缩略图 可以是网络地址、File、Integer(资源引用)、Bitmap、byte[]字节数组
     * @param title 标题
     * @param umShareListener 回调
     */
    public void shareMusic(Activity activity, SHARE_MEDIA type,String musicurl, Object musicThumb,
                           String title,String description, UMShareListener umShareListener)
    {
        UMusic music = new UMusic(musicurl);
        UMImage image;
        music.setTitle(title);//音乐的标题

        if(musicThumb instanceof String)
        {
            image = new UMImage(activity, (String) musicThumb);
            music.setThumb(image);//视频的缩略图
        }else if (musicThumb instanceof File)
        {
            File file = (File)musicThumb;
            image = new UMImage(activity, file);//本地图片
            music.setThumb(image);
        }
        else if (musicThumb instanceof Integer)
        {
            Integer drawableId = (Integer)musicThumb;
            image = new UMImage(activity, drawableId);//资源图片
            music.setThumb(image);
        }
        else if (musicThumb instanceof Bitmap)
        {
            Bitmap bmp = (Bitmap)musicThumb;
            image = new UMImage(activity, bmp);//位图
            music.setThumb(image);
        }
        else if (musicThumb instanceof byte[])
        {
            byte[] buffer = (byte[])musicThumb;
            image = new UMImage(activity, buffer);//网络图片
            music.setThumb(image);
        }
        music.setDescription(description);//音乐的描述

        new ShareAction(activity)
                .setPlatform(type)
                .withMedia(music)
                .setCallback(umShareListener)
                .share();
    }

    /***
     * 分享视频
     * @param activity
     * @param type 分享平台
     * @param videoUrl 视屏地址
     * @param videoThumb 缩略图，可以是网络地址、File、Integer(资源引用)、Bitmap、byte[]字节数组
     * @param title 标题
     * @param umShareListener   回调
     */
    public void shareVideo(Activity activity, SHARE_MEDIA type, String videoUrl, Object videoThumb, String title,UMShareListener umShareListener)
    {
        UMVideo video = new UMVideo(videoUrl);
        UMImage image;
        video.setTitle(title);//视频的标题
        if(videoThumb instanceof String)
        {
            image = new UMImage(activity, (String) videoThumb);
            video.setThumb(image);//视频的缩略图
        }else if (videoThumb instanceof File)
        {
            File file = (File)videoThumb;
            image = new UMImage(activity, file);//本地图片
            video.setThumb(image);
        }
        else if (videoThumb instanceof Integer)
        {
            Integer drawableId = (Integer)videoThumb;
            image = new UMImage(activity, drawableId);//资源图片
            video.setThumb(image);
        }
        else if (videoThumb instanceof Bitmap)
        {
            Bitmap bmp = (Bitmap)videoThumb;
            image = new UMImage(activity, bmp);//位图
            video.setThumb(image);
        }
        else if (videoThumb instanceof byte[])
        {
            byte[] buffer = (byte[])videoThumb;
            image = new UMImage(activity, buffer);//网络图片
            video.setThumb(image);
        }
        video.setDescription(videoUrl);//视频的描述

        new ShareAction(activity)
                .setPlatform(type)
                .withMedia(video)
                .setCallback(umShareListener)
                .share();
    }

    /***
     * 分享链接
     * @param activity
     * @param type 平台
     * @param urlLink 要分享的链接
     * @param umShareListener 回调
     */
    public void shareLink(Activity activity, SHARE_MEDIA type, String urlLink,String text,  UMShareListener umShareListener)
    {
//        UMImage img = new UMImage(activity, "http://img3.duitang.com/uploads/item/201502/21/20150221162526_Krfzk.jpeg");
        new ShareAction(activity)
                .setPlatform(type)
                .withText(text)
                .setCallback(umShareListener)
                .share();
    }

    /***
     *三方登录
     * @param mContext
     * @param type 平台 暂时只支持微信、qq、新浪微博 （type为微信时， callback参数传泛型UMWXResp，type为QQ时，用泛型UMQQResp，type为SINA时，用泛型UMSINAResp）
     * @param callback  回调
     */
    public void Login(final Activity mContext, final SHARE_MEDIA type, final UMResultCallback callback)
    {
        final UMShareAPI mShareAPI = UMShareAPI.get(mContext);
        //先进行授权
        mShareAPI.doOauthVerify(mContext, type, new UMAuthListener()
        {
            @Override
            public void onStart(SHARE_MEDIA share_media)
            {
                callback.onStart();
            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map)
            {
                //成功后获取平台信息
                mShareAPI.getPlatformInfo(mContext, type, new UMAuthListener()
                {
                    @Override
                    public void onStart(SHARE_MEDIA share_media)
                    {

                    }

                    @Override
                    public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map)
                    {
                        StringBuffer sb = new StringBuffer("{");
                        Set<String> set = map.keySet();
                        for (Iterator<String> it = set.iterator(); it.hasNext();)
                        {
                            String key = it.next();
                            String value = map.get(key);
                            sb.append("\""+key+"\":\""+value+"\",");
                        }
                        String temp = sb.toString();
                        String content = temp.substring(0, temp.lastIndexOf(",")) + "}";

                        if(type == SHARE_MEDIA.WEIXIN)
                        {
                            Gson g = new Gson();
                            UMWXResp resp = g.fromJson(content, UMWXResp.class);
                            callback.onComplete(resp);
                        }else if(type == SHARE_MEDIA.QQ)
                        {
                            Gson g = new Gson();
                            UMQQResp resp = g.fromJson(content, UMQQResp.class);
                            callback.onComplete(resp);
                        }else if(type == SHARE_MEDIA.SINA)
                        {
                            UMSINAResp resp = new UMSINAResp();
                            String id = map.get("id");
                            resp.setId(id);
                            String screen_name = map.get("screen_name");
                            resp.setScreen_name(screen_name);
                            String location = map.get("location");
                            resp.setLocation(location);
                            String profile_image_url = map.get("avatar_hd");
                            resp.setProfile_image_url(profile_image_url);
                            String gender = map.get("gender");
                            resp.setGender(gender);
                            String followers_count = map.get("bi_followers_count");
                            resp.setFollowers_count(followers_count);
                            String friends_count = "0";
                            resp.setFriends_count(friends_count);
                            callback.onComplete(resp);
                        }
                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, int i, Throwable throwable)
                    {
                        callback.onError(throwable);
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media, int i)
                    {
                        callback.onCancel("登录取消");
                    }
                });
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable)
            {
                callback.onError(throwable);
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i)
            {
                callback.onCancel("登录取消");
            }
        });
    }

    /***
     * 注销登录
     * @param mContext
     * @param type 平台
     * @param callback 回调
     */
    public static void LogOff(Activity mContext, final SHARE_MEDIA type, final UMResultCallback<String> callback)
    {
        UMShareAPI mShareAPI = UMShareAPI.get(mContext);
        mShareAPI.deleteOauth(mContext, type, new UMAuthListener(){

            @Override
            public void onStart(SHARE_MEDIA share_media)
            {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map)
            {
                callback.onComplete("注销成功");
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable)
            {
                callback.onError(throwable);
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i)
            {
                callback.onCancel("取消");
            }
        });
    }

    public static Object mapToObject(Map<String, String> map, Class<?> beanClass) throws Exception
    {
        if (map == null)
            return null;

        Object obj = beanClass.newInstance();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields)
        {
            int mod = field.getModifiers();
            if (Modifier.isStatic(mod) || Modifier.isFinal(mod))
            {
                continue;
            }
            field.setAccessible(true);
            field.set(obj, map.get(field.getName()));
        }

        return obj;
    }

    /***
     * 判断微信是否安装
     *
     * @param context
     * @param WX_ID
     * @return
     */
    public static boolean isWXAppInstalledAndSupported(Context context, String WX_ID)
    {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(context, null);
        msgApi.registerApp(WX_ID);
        return msgApi.isWXAppInstalled() && msgApi.isWXAppSupportAPI();
    }

    public void onActivityResult(Context context, int requestCode, int resultCode, Intent data)
    {
        UMShareAPI.get(context).onActivityResult(requestCode, resultCode, data);
    }

    public static abstract class UMResultCallback<T>
    {

        Type mType;

        public UMResultCallback()
        {
            mType = getSuperclassTypeParameter(getClass());
        }

        public static Type getSuperclassTypeParameter(Class<?> subclass)
        {
            Type superclass = subclass.getGenericSuperclass();
            if (superclass instanceof Class)
            {
                throw new RuntimeException("泛型缺少类型");
            }
            ParameterizedType parameterized = (ParameterizedType) superclass;
            return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
        }

        public abstract void onStart();

        public abstract void onComplete(T result);

        public abstract void onError(Throwable e);

        public abstract void onCancel(String str);
    }
}
